package cn.jwelll.bxcstock.ui.login;
import cn.jwelll.bxcstock.base.BasePresenter;
import cn.jwelll.bxcstock.common.ConstValue;
import cn.jwelll.bxcstock.common.StockApp;
import cn.jwelll.bxcstock.net.ApiMiddleHelper;
import cn.jwelll.bxcstock.net.listener.DataCallBackListener;
import cn.jwelll.bxcstock.util.LogUtil;
import cn.jwelll.bxcstock.util.SPUtils;
import com.google.gson.JsonObject;
import io.reactivex.Flowable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {
    public LoginPresenter() {
    }

    @Override
    public void start() {
    }

    @Override
    public void login(String name, String pass) {
        Map<String, String> biddingMap = new HashMap<>();
        biddingMap.put("userName", name);
        biddingMap.put("password", pass);
        Flowable<JsonObject> flowable = apiStrores.login(biddingMap);
        ApiMiddleHelper.getInstance().toNetIo2Main(null,flowable, new DataCallBackListener() {
            @Override
            public void onSuccess(String json) {
                LogUtil.i("TAG", "login-" + json);
                LogUtil.d("login-onSuccess-" + json);
//                {"result":{"token":"sd","name":"李博","userName":"000156"},"targetUrl":null,"success":true,"error":null,"unAuthorizedRequest":false,"__abp":true}
                try {
                    JSONObject object = new JSONObject(json);

                    SPUtils.putString(StockApp.Companion.getInstance(), ConstValue.URL_TOKEN, object.getString("token"));
                    SPUtils.putString(StockApp.Companion.getInstance(), ConstValue.LOGIN_COUNT, name);
                    SPUtils.putString(StockApp.Companion.getInstance(), ConstValue.USER_NAME, object.getString("name"));
                    SPUtils.putString(StockApp.Companion.getInstance(), ConstValue.WARE_HOUSE_NAME, object.getInt("wareHouse")==10?"W61厂区库":"W62生铁库");
                    SPUtils.putString(StockApp.Companion.getInstance(), ConstValue.LOGIN_PASS, pass);
                    SPUtils.putBoolean(StockApp.Companion.getInstance(), ConstValue.LOGIN_STATE, true);
                    if (getView() != null) {
                        getView().loginSuccess("");
                    }
                } catch (JSONException e) {
                    onFailure("数据解析错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String msg) {
                SPUtils.putBoolean(StockApp.Companion.getInstance(), ConstValue.LOGIN_STATE, false);
                LogUtil.d("login-onFailure-" + msg);
                if (getView() != null) {
                    getView().loginFailde(msg);
                }
            }
        });
    }
}
